from google.appengine.api import users

try:
    import cStringIO as StringIO
except ImportError:
    import StringIO

import urllib, urllib2
import datetime
from datetime import timedelta
import time
import random 

from googlemaps import GoogleMaps
try:
    from django.utils import simplejson as json
except ImportError:
    import json as json

from pytz import timezone
import pytz
from datetime import datetime
from pytz import gae

from Location import *
    
def TranslateAddressToCoordinates(address):
    gmaps = GoogleMaps("ABQIAAAAz7jb75cXS8LyZmZCu0w-MhRNi9qYayfUdT53zJYzeJQRmgxJEhRsNj3r2ldNbXpOOYdXHsRmQhE61g")
    #print address
    lat, lng = gmaps.address_to_latlng(address)
    return (lat, lng)

def GetMapCode(location, gpsLocation):

    if not location:
        return ""

    from pymaps import Map, PyMap, Icon # import the libraries

    lat = location.lat
    lng = location.lng

    # Create a map - pymaps allows multiple maps in an object
    tmap = Map()
    tmap.zoom = 15

    # Inserts html into the hover effect
    pointhtml = "Your zentienz is here!"

    # Add the point to the map
    point = (lat, lng, pointhtml, '')
    tmap.setpoint(point)
    tmap.center = (lat, lng)

    # Add gps position
    if gpsLocation != None:
        point = (gpsLocation.lat, gpsLocation.lng, "GPS location", '')
        tmap.setpoint(point)

    gmap = PyMap(key="ABQIAAAAz7jb75cXS8LyZmZCu0w-MhRNi9qYayfUdT53zJYzeJQRmgxJEhRsNj3r2ldNbXpOOYdXHsRmQhE61g", maplist=[tmap])

    # pymapjs exports all the javascript required to build the map!
    return gmap.pymapjs()

def SetLocationCoordinates(location):
    gmaps = GoogleMaps("ABQIAAAAz7jb75cXS8LyZmZCu0w-MhRNi9qYayfUdT53zJYzeJQRmgxJEhRsNj3r2ldNbXpOOYdXHsRmQhE61g")
    address = "%s, %s, %s, denmark" % (location.street, location.number, location.zipCode )
    try:
        location.lat, location.lng = gmaps.address_to_latlng(address)
    except:
        pass
 
def SetPersonLocationCoordinates(person):
    gmaps = GoogleMaps("ABQIAAAAz7jb75cXS8LyZmZCu0w-MhRNi9qYayfUdT53zJYzeJQRmgxJEhRsNj3r2ldNbXpOOYdXHsRmQhE61g")
    if person.homeLocation:
        address = "%s, %s, %s, denmark" % (person.homeLocation.street, person.homeLocation.number, person.homeLocation.zipCode )
        person.homeLocation.lat, person.homeLocation.lng = gmaps.address_to_latlng(address)
    if person.workLocation:
        address = "%s, %s, %s, denmark" % (person.workLocation.street, person.workLocation.number, person.workLocation.zipCode )
        person.workLocation.lat, person.workLocation.lng = gmaps.address_to_latlng(address)
    if person.currentLocation:
        address = "%s, %s, %s, denmark" % (person.currentLocation.street, person.currentLocation.number, person.currentLocation.zipCode )
        person.currentLocation.lat, person.currentLocation.lng = gmaps.address_to_latlng(address)

def getGaussDistDate(date, varianceInSeconds):
    dSec = random.gauss(0, varianceInSeconds)
    return date - datetime.timedelta(seconds=dSec)

def interpolateLocation(p1, p2, f):
    dlat = p2.lat - p1.lat
    dlng = p2.lng - p1.lng
    l = Location()
    l.lat = p1.lat + f*dlat
    l.lng = p1.lng + f*dlng
    return l

def PrintTime(date):
    return "%i:%02i" % (date.hour, date.minute)

def localDatetime(year, month, day, hour, min):
    d = datetime(year, month, day, hour, min, 0)
    d = toMyTZ(d)
    return d

def toMyTZ(date):
    tz = myTZInfo()
    d_tz = tz.normalize(tz.localize(date))
    return d_tz

def toUTC(date):
    tz = myTZInfo()
    utc = pytz.timezone('UTC')
    d_tz = tz.normalize(tz.localize(date))
    d_utc = d_tz.astimezone(utc)
    return d_utc

def fromUTC(date):
    utc = pytz.timezone('UTC')
    if date.tzinfo == None:
        date = datetime(date.year,date.month,date.day,date.hour,date.minute,date.second,tzinfo=utc)
    tz = myTZInfo()
    d_tz = utc.normalize(date)
    localetime = d_tz.astimezone(tz)
    return localetime

def myTZInfo():
    return timezone("Europe/Berlin")
    #return timezone("Europe/Copenhagen")

def TimeNowUTC():
    return datetime.now(timezone('UTC'))

def addUTC(date):
    return date.replace(tzinfo=pytz.timezone('UTC'))

def TravelTime(directions):
    return timedelta(seconds=directions['Directions']['Duration']['seconds'])

def Directions(start, end):
    gmaps = GoogleMaps("ABQIAAAAz7jb75cXS8LyZmZCu0w-MhRNi9qYayfUdT53zJYzeJQRmgxJEhRsNj3r2ldNbXpOOYdXHsRmQhE61g")
    d = gmaps.directions("Frejasgade 7, 2200 kbh, Denmark", "Agern Alle 5, 2970, Denmark")
    #print d['Directions']['Distance']['meters']
    #print d['Directions']['Duration']['seconds']
    return d

def TimeNow():
    d = datetime.now(timezone('UTC'))
    return fromUTC(d)

def PositionAlongDirections(directions, dt):
    duration = timedelta()
    i = 0
    for step in directions['Directions']['Routes'][0]['Steps']:
        duration = duration + timedelta(seconds=step['Duration']['seconds'])
        #print 0, duration, dt, duration-dt, " //// ", (duration-dt).seconds
        if duration > dt:
            f = 1.0 - float((duration-dt).seconds)/float(step['Duration']['seconds'])
            p1 = step['Point']['coordinates']
            p2 = directions['Directions']['Routes'][0]['Steps'][i+1]['Point']['coordinates']
            #print p1
            #print p2
            dx = p2[0] - p1[0]
            dy = p2[1] - p1[1]
            #print dx, dy
            p =  (p1[0] + f*dx, p1[1] + f*dy)
            return p
        i = i + 1

def DeleteTable(table):
    try:
        while True:
            q = db.GqlQuery("SELECT __key__ FROM %s" % table)
            if q.count() == 0:
                return
            db.delete(q.fetch(200))
            time.sleep(0.5)
    except Exception, e:
        return "Exception: " + repr(e)
